package com.myapp.util;

import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.collections.map.LRUMap;
import org.apache.commons.collections.OrderedMapIterator;

class ShoppingCartEntry {		
	private Date buildDate  = null ;	
	private Date updateDate = null ;	
	private Map<Integer,Integer> cart = new HashMap<Integer,Integer>();
	
	public Date getBuildDate() {
		return buildDate;
	}
	public void setBuildDate(Date buildDate) {
		this.buildDate = buildDate;
	}
	public Date getUpdateDate() {
		return updateDate;
	}	
	public void setUpdateDate(Date updateDate) {
		this.updateDate = updateDate;
	}	
	public void removeItem(int id){
		cart.remove(id);
	}	
	public void updateItem(int id,int num){
		cart.put(id, num);
	}	
	public Map<Integer, Integer> getCart() {
		return cart;
	}
	public void setCart(Map<Integer, Integer> cart) {
		this.cart = cart;
	}
}

public class ShoppingCartRegister {		
	private static ShoppingCartRegister inst = null;	
	protected LRUMap cartRegister = new LRUMap();
	
	public synchronized static ShoppingCartRegister instance(){
		if(inst == null){
			inst = new ShoppingCartRegister();
		}
		return inst;
	}
	
	private ShoppingCartEntry buildShoppingCart(String sessionId){
		ShoppingCartEntry shoppingCart = (ShoppingCartEntry)cartRegister.get(sessionId);
		if(shoppingCart == null){
			Date date = new Date();
			shoppingCart = new ShoppingCartEntry();			
			shoppingCart.setBuildDate(date);
			shoppingCart.setUpdateDate(date);			
			cartRegister.put(sessionId, shoppingCart);			
		}
		return shoppingCart;
	}
	
	public void updateShoppingItem(String sessionId,int itemId,int num){		
		ShoppingCartEntry shoppingCart = (ShoppingCartEntry)cartRegister.get(sessionId);
		if(shoppingCart == null){
			shoppingCart = buildShoppingCart(sessionId);		
		}
		shoppingCart.updateItem(itemId, num);
	}
	
	public Map<Integer, Integer> getCart(String sessionId){
		ShoppingCartEntry shoppingCart = (ShoppingCartEntry)cartRegister.get(sessionId);
		if(shoppingCart == null){
			shoppingCart = buildShoppingCart(sessionId);			
		}
		return shoppingCart.getCart();
	}
	
	public void removeShoppingItem(String sessionId){		
		cartRegister.remove(sessionId);
	}
			
	public static void main(String[] args){
		LRUMap map = new LRUMap();
		map.put(11,"test");
		map.put(12,"test222");
		map.put(13,"test333");
		map.put(14,"test444");
	    map.put(14,"$$$$0000");
		map.put(14,"$$$$4444");
		OrderedMapIterator it = map.orderedMapIterator();
		
		while(it.hasNext()){
			it.next();
			//System.out.println("key: " + it.getKey() + ",value=" + it.getValue());
			it.remove();
		}
		System.out.println("size = " + map.size());
	}
}
